import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Invoice from '@/views/Invoice.vue'
import Contract from '@/views/Contract.vue'
import General from '@/views/General.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/invoice',
    name: 'invoice',
    component: Invoice
  },
  {
    path: '/contract',
    name: 'contract',
    component: Contract
  },
  {
    path: '/general',
    name: 'General',
    component: General
  }
]

// 创建路由对象
const router = new VueRouter({ routes })

router.beforeEach((to, from, next) => {
  // to是将要访问的路径
  // from代表从哪个路径跳转而来
  // next是一个函数，代表放行，next('/login') 是强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

// 挂载路由导航守卫
// 导出实例供入口文件使用
export default router
